import { setCreepStand } from '@/global/move';
import { TaskBase } from '../TaskBase';

export class TaskHarvest extends TaskBase {
    shouldRun(creep: Creep): boolean {
        if (creep.body.some(bp => bp.type === WORK && bp.hits > 0)) {
            if (creep.body.some(bp => bp.type === CARRY)) {
                return creep.store.getFreeCapacity() > 0;
            }
            else {
                return true;
            }
        }
        else {
            return false;
        }
    }

    _run(creep: Creep) {
        const target = <Source | Deposit | Mineral>this.target;
        const result = creep.harvest(target);
        if (result === OK) {
            setCreepStand(creep.name, true);
            return ERR_UNFINISHED;
        }
        else if (result === ERR_NOT_ENOUGH_RESOURCES) {
            // 没有资源，结束任务
            if ('energy' in target) {
                setCreepStand(creep.name, false);
                creep.makeSuspend(target.ticksToRegeneration + 1);  // 节省 cpu
            }
            return OK;
        }
        else if (result === ERR_TIRED) {
            // extractor 在冷却
            return ERR_UNFINISHED;
        }
        else if (result === ERR_NOT_IN_RANGE) {
            return ERR_NOT_IN_RANGE;
        }
        else {
            return OK;
        }
    }
}
